package my.edu.security.shiroservice;

import cn.hutool.json.JSONUtil;
import my.edu.common.utils.JsonUtils;
import my.edu.common.utils.RedisUtils;
import my.edu.security.userEntity.JWTToken;
import my.edu.security.userEntity.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class SysUserTokenServiceImpl implements SysUserTokenService {
    /**
     * //	 * 12小时后过期
     * //
     */
    private final static int EXPIRE = 3600 * 12;

    @Autowired
    RedisUtils redisUtils;


    public String createToken(Long userId) {
        //用户token
        String token;

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //redis的键是loginUser，hash的键是userid（从token中解析获得），存的是UserToken

        //判断是否生成过token
        UserToken tokenEntity = JsonUtils.parseObject(redisUtils.hMGet("loginUser", userId + ""),UserToken.class);
        if (tokenEntity == null) {
            //生成一个token并保存token
            token = JWTToken.getUserJWTString(userId);

            tokenEntity = new UserToken();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateDate(now);
            tokenEntity.setExpireDate(expireTime);

            Map<String, Object> tokenr = new HashMap<>();
            tokenr.put(userId + "", JSONUtil.toJsonStr(tokenEntity));
            redisUtils.hMSet("loginUser", tokenr);
        } else {
            //判断token是否过期
            if (tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) {
                //token过期，重新生成token
                token = JWTToken.getUserJWTString(userId);
                tokenEntity.setToken(token);
            } else {
                token = tokenEntity.getToken();
            }

            tokenEntity.setUpdateDate(now);
            tokenEntity.setExpireDate(expireTime);

            //更新token
            Map<String, Object> tokenr = new HashMap<>();
            tokenr.put(userId + "", JSONUtil.toJsonStr(tokenEntity));
            redisUtils.hMSet("loginUser", tokenr);
        }


        return token;
    }

    public void logout(Long userId) {
        redisUtils.hDel("loginUser", userId);
    }


}